// components/login/loginModule.js
let app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    canIUseGetUserProfile: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    isAgreement: false,
    loginBol: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 是否选中 登录协议
     */
    checkboxChange(e) {
      let self = this;
      let val = e.detail.value;
      let isAgreement = self.data.isAgreement;
      if (val.length > 0) {
        isAgreement = true;
      } else {
        isAgreement = false;
      }
      self.setData({
        isAgreement: isAgreement
      })
    },
phoneLoginClick(e){
    if (!e.detail.iv) {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({
      title: '登录中',
    })
    var that = this;
    var code = e.detail.code; //获取手机号授权code
    app.getDaoPost('api/FeijiuApp/Feijiu_XCX_GetPhoneNumber', {code:e.detail.code}, function (r) {
      if (r.code == 200) {
        wx.setStorageSync('FjLoginLog', r.data);
        app.tishi(r.message);
        wx.setStorageSync('FjLoginLog', r.data);
        setTimeout(function () {
          that.triggerEvent('onshow')
        }, 1000)
      } else {
        app.tishi(r.message)
      }
    })
  },
  otherPhoneLogin:function(){
    wx.navigateTo({
      url: '/pages/login/newLogin'
    })
  },
    /**
     * 微信登录
     */
    wxLogin(e) {
      console.log(e)
      let self = this;
      let isAgreement = self.data.isAgreement;
      let canIUseGetUserProfile = self.data.canIUseGetUserProfile;
      if (!isAgreement) {
        wx.showToast({
          title: '请先阅读并勾选协议',
          icon: "none"
        })
        return false;
      }
      // // 开始登录
      // wx.showLoading({
      //   title: '请稍后...',
      // })
      // if (!canIUseGetUserProfile) {
      //   e = e.detail
      // }
      // let code = app.globalData.userInfor.code;
      // let session = app.globalData.userInfor.sessionKey;
      // let unionid = app.globalData.userInfor.unionid
      // if (e.encryptedData != undefined && code != undefined && session != undefined) {
      //   let data = {
      //     code: code,
      //     encryptedData: e.encryptedData,
      //     session_key: session,
      //     iv: e.iv,
      //     state: 1,
      //     auth_source: 'zaisubao_xcx',
      //     unionid: unionid
      //   }
      //   self.decodeWx(data, 'decodeWx');
      // } else {
        
      //   wx.hideLoading();
      // }

    },

    /**
     * 无勾选协议时执行
     */
    isAgreementFn() {
      let self = this;
      let isAgreement = self.data.isAgreement;
      if (!isAgreement) {
        wx.showToast({
          title: '请先阅读并勾选协议',
          icon: "none"
        })
        return false;
      }
    },

    /**
     * 登录 -- 解密
     */
    decodeWx(data, keys) {
      let self = this;
      console.log(data, "-************");
      // return false;
      app.agriknow[keys](data)
        .then(que => {
          console.log(1)
          wx.hideLoading();
          // debugger
          if (que.resultCode != 1 && keys == 'decodeWx') {
            wx.showModal({
              title: '温馨提示',
              content: '微信登录失败',
            })
            return false;
          }
          //微信 登录 手机
          if (!que.binding && keys == 'decodeWx') {
            if (que.resultCode == 960613301) {
              wx.showModal({
                title: '温馨提示',
                content: '微信登录失败请稍后再试！',
              })
              return false;
            }
            console.log(que)
            self.setData({
              loginBol: false,
              bindIcon: que.head_img,
              nickname: que.nickname,
              uid: que.uid
            })
            return false;
          }

          //绑定手机号
          if (que.resultCode == 1 && que.binding) {
            app.globalData.baodou = que.baodou;
            self.setData({
              reqMsg: ""
            })
            wx.setStorageSync('userDetail', que)
            try {
              app.getMemberCode(function () {
                self.triggerEvent("typeEvent", {
                  islogInActive: true
                });
                self.setData({
                  loginBol: true
                })
              });
              // self.onLoad()
              console.log("que获取到的数据", que)
              // wx.setStorageSync("userDetail", que)
              // wx.switchTab({
              //   url: '../index/index',
              // })
            } catch (e) {console.log("try",e)}
          }

        })
        .catch(err => {
          console.log("调取登录接口失败：", err)
          try {
            //手机登录
            if (!err.data.binding && keys == 'bindPhone' && err.data.resultCode == 960613018) {
              wx.showModal({
                title: '温馨提示',
                content: "检测到您还未注册账号，是否前往注册！",
                success: res => {
                  if (res.confirm) {
                    //点击了确定按钮
                    wx.navigateTo({
                      url: '../signInType/signInType',
                    })
                  }
                }
              })
              return false;
            }
            wx.showToast({
              title: err.data.resultMessage,
              icon: "none"
            })
          } catch (fail) {
            wx.showToast({
              title: "微信登录失败请稍后再试！",
              icon: "none"
            })
          }
        })
    },

    /**
     * 获取手机号码
     */
    bindPhoneNum: function (e) {
      let self = this;
      let encryptedData = e.detail.encryptedData;
      let iv = e.detail.iv;
      wx.showLoading({
        title: '请稍后...',
      })
      let code = app.globalData.userInfor.code;
      let session = app.globalData.userInfor.sessionKey;
      let uid = self.data.uid;
      if (encryptedData != undefined && code != undefined && session != undefined && uid != undefined) {
        let data = {
          code: code,
          encryptedData: encryptedData,
          session_key: session,
          iv: iv,
          state: 1,
          auth_source: 'zaisubao_xcx',
          uid: uid
        }
        self.decodeWx(data, 'bindPhone');
      } else {
        wx.hideLoading();
      }
    },
    toUserXy:function () {
      wx.navigateTo({
        url: '../webBanner/webBanner?url=https://m.zaisubao.cn/h5/servicexy&title=再塑宝网服务协议'
      })
    },
    toUserYstk:function () {
      wx.navigateTo({
        url: '../webBanner/webBanner?url=https://m.zaisubao.cn/h5/zaisubao&title=隐私政策'
      })
    },
    /**
     * 新版登录
     */
    getUserProfileFn() {
      let self = this;
      let isAgreement = self.data.isAgreement;
      if (!isAgreement) {
        wx.showToast({
          title: '请先阅读并勾选协议',
          icon: "none"
        })
        return false;
      }
      wx.getUserProfile({
        desc: '获取你的昵称、头像、地区及性别',
        success: (res) => {
          self.wxLogin(res);
        }
      })
    },
    toyszc:function () {
      wx.navigateTo({
        url: '/pages/login/toweb?url=https://apps.feijiu.net/app/yssm/'
      })  
    },
    tozcxy:function () {
      wx.navigateTo({
        url: '/pages/login/toweb?url=https://apps.feijiu.net/app/fwxy'
      })  
    },
    bindGetUserInfo: function(e) {
      let that = this
      let isAgreement = that.data.isAgreement;
      let canIUseGetUserProfile = that.data.canIUseGetUserProfile;
      if (!isAgreement) {
        wx.showToast({
          title: '请先阅读并勾选协议',
          icon: "none"
        })
        return false;
      }
      console.log(e)
      console.log('loginUSER')
   
      var info = e.detail;
      var openid = wx.getStorageSync('openid');
      if (info.errMsg == 'getUserInfo:ok') {
        var api_input = {
          Ly:1,
          UnionID:openid.unionid,
          OpenID:openid.openid,
          nickName:info.userInfo.nickName,
          AesData:info.encryptedData,
          AesIv:info.iv,
          AesKey:openid.session_key,
          IP:wx.getStorageSync('id'),
          sbid:'',
          sbtype:wx.getStorageSync('sbtype'),
          sbname:wx.getStorageSync('sbname')
        }
        app.getDaoPostN('api/FeijiuApp/PostLogin_WxLog',api_input,function (r) {     
          if (r.code == 200) {
            if (r.data.IsDl == 0) {
              app.tishi('登录失败，该微信未绑定Feijiu账号!');
              wx.setStorageSync('userinfo',info);
              wx.navigateTo({url: '/pages/login/binduser'})
            }else{
              app.tishi(r.data.Mess);
              wx.setStorageSync('FjLoginLog',r.data);
              setTimeout(function () {
                that.triggerEvent('onshow')
              }, 1000)             
            }
          }else{
            app.tishi('微信登录失败!')
  
          }
        })
  
      }else{
        app.tishi('微信登录失败,请允许Feijiu网获取您的微信信息!')
      }
    }
  },
 
})